package com.xtinno.common;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import net.sourceforge.pinyin4j.PinyinHelper;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class JsonKeyChineseToPinyin {
    // 将中文字符转换为驼峰格式的拼音
    public static String toCamelCasePinyin(String chinese) {
        StringBuilder sb = new StringBuilder();
        List<String> words = new ArrayList<>();

        for (char c : chinese.toCharArray()) {
            if (c >= '\u4e00' && c <= '\u9fa5') {
                String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c);
                if (pinyinArray != null) {
                    String word = pinyinArray[0].replaceAll("\\d", "");
                    words.add(word);
                }
            } else {
                // 如果包含非中文字符（如空格、数字等），按分隔符处理
                if (!words.isEmpty()) {
                    combineAndAppend(sb, words);
                    words.clear();
                }
                sb.append(c);
            }
        }

        if (!words.isEmpty()) {
            combineAndAppend(sb, words);
        }

        return sb.toString();
    }
    private static void combineAndAppend(StringBuilder sb, List<String> words) {
        if (words.isEmpty()) return;

        sb.append(words.get(0)); // 第一个单词全小写
        for (int i = 1; i < words.size(); i++) {
            String word = words.get(i);
            if (!word.isEmpty()) {
                sb.append(Character.toUpperCase(word.charAt(0)) + word.substring(1));
            }
        }
    }
    // 递归转换JSON对象中的key
    public static JSONObject convertJsonKeys(JSONObject jsonObject) {
        JSONObject result = new JSONObject();
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            // TODO: 驼峰
            String newKey = toCamelCasePinyin(entry.getKey().replace(" ",""));
            Object value = entry.getValue();
            // TODO: 这里 json array 的判断
            if (value instanceof JSONObject) {
                result.put(newKey, convertJsonKeys((JSONObject) value));
            } else if (value instanceof JSONArray) {
                result.put(newKey, convertJsonArray((JSONArray) value));
            } else {
                result.put(newKey, value);
            }
        }
        return result;
    }
    // 递归处理 JSONArray
    public static JSONArray convertJsonArray(JSONArray jsonArray) {
        JSONArray result = new JSONArray();
        for (Object item : jsonArray) {
            if (item instanceof JSONObject) {
                result.add(convertJsonKeys((JSONObject) item));
            } else if (item instanceof JSONArray) {
                result.add(convertJsonArray((JSONArray) item));
            } else {
                result.add(item);
            }
        }
        return result;
    }
}
